import React, {Component} from 'react';
import { Button } from 'antd'
import TheQueryForm from '@/components/TheQueryForm';
import TheButton from '@/components/TheButton';
import TheTable from '@/components/TheTable';
import TheTableExtend from '@/components/TheTableExtend';
import ThePagination from '@/components/ThePagination';
import { apiGetTimedTaskPage, apiGetCouponTimerCenterDel } from '@/request/couponManagement';
import store from "@/store/store";
import _ from 'lodash';
import moment from 'moment'
import { getDateTime3 } from '@/utils/getDate';


class TimedTask extends Component {

    constructor() {
        super()
        this.queryFormRef = React.createRef()
        this.state = {
            isShowQueryForm: true,
            tableSource: [],
            total: 0,
            columns: [{
                title: '任务id',
                dataIndex: 'couponTimerCenterId',
                key: 'couponTimerCenterId',
            }, {
                title: '发送时间',
                dataIndex: 'pushDateTime',
                key: 'pushDateTime',
             
            }, {
                title: '状态',
                dataIndex: 'timerStatus',
                key: 'timerStatus',
                render:((text)=>{
                    let status
                    switch (text) {
                        case 0:
                            status = '未开始'
                            break;
                        case 1:
                            status = '进行中'
                            break;
                        case 2:
                            status = '已完成'
                            break;
                        default:
                            break;
                    }
                    return status
                })
            }, {
                title: '结果',
                dataIndex: 'timerResult',
                key: 'timerResult',
                render:((text)=>{
                    let result
                    switch (text) {
                        case 0:
                            result = '未执行'
                            break;
                        case 1:
                            result = '成功'
                            break;
                        case 2:
                            result = '部分成功'
                            break;
                        case 3:
                            result = '失败'
                            break;
                        default:
                            break;
                    }
                    return result
                })
            }, {
                title: '最近修改时间',
                dataIndex: 'updateTimeString',
                key: 'updateTimeString',
                render:(text)=>{
                    return (
                        <>{text?moment(text).format('yyyy-MM-DD HH:mm'):'/'}</>
                    )
                }
            }, {
                title: '操作',
                dataIndex: 'operate',
                fix: 'right',
                key: 'operate',
                render: (text, record) => {
                    return (
                        <div>
                            { record.timerStatus === 0 && <TheButton haspermi={["couponManagement:task:edit"]} onClick={() => this.props.history.push(`/couponManagement/timedTask/detail/${record.couponTimerCenterId}?type=edit&&time=${record.pushDateTime}`)}>修改</TheButton> }
                            <TheButton  haspermi={["couponManagement:task:view"]} onClick={() => this.props.history.push(`/couponManagement/timedTask/view/${record.couponTimerCenterId}?type=view&&time=${record.pushDateTime}`) }>查看</TheButton>
                            { record.timerStatus === 0 && <TheButton haspermi={["couponManagement:task:del"]} onClick={()=>{this.deletedTask(record.couponTimerCenterId)}} >删除</TheButton>}
                            { record.timerStatus !== 0 && <TheButton haspermi={["couponManagement:task:result"]} onClick={()=>this.props.history.push(`/couponManagement/timedTask/result/${record.couponTimerCenterId}`)} >发送结果</TheButton>}
                        </div>
                    )
                }
            }],
            filterColumns: [],
            queryFormOptions: [
                { field: 'couponTimerCenterId', label: '任务id', placeholder: '请输入任务id', require: false, rules: [{pattern: /^[1-9]*[1-9][0-9]*$/, message:'只允许输入非0开始的数字'}], type: 'Input', defaultValue: '' },
                { field: 'taskTime', label: '任务时间', placeholder: '任务时间', require: false, rules: [], type: 'RangePicker', defaultValue: '' },
                { field: 'status', label: '状态', placeholder: '状态', require: false, rules: [], type: 'Select', defaultValue: '', options: [{
                    label: '未开始',
                    value: '0',
                }, {
                    label: '进行中',
                    value: '1',
                }, {
                    label: '已完成',
                    value: '2',
                }]},
            ],
            queryFormFieldsValue: {},
            status: {
                0: '未开始',
                1: '进行中',
                2: '已成功',
            },
            pageData:{
                pageNo: 1,
                pageSize: 10,
            }
            
        }
    }

    componentDidMount() {
        this.setState({
            filterColumns: this.state.columns,
        })
        let searchParams = store.getState().searchValue
        let { pageNo, pageSize, queryFormFieldsValue, pathName } = searchParams
        if (searchParams && pageNo && pathName === 'tasklist') {
            let { pageNo, pageSize, code } = searchParams
            this.setState({
                code,
                pageData: {
                    pageNo: pageNo, pageSize: pageSize
                }
            }, () => {
                this.queryFormRef.onSetDefault({ ...queryFormFieldsValue })
                this.getTimedTaskList()
            })
        } else {
            this.getTimedTaskList()
        }
        
    }
    // 重置
    onReset() {
        this.setState({
            queryFormFieldsValue:{}
        })
        this.onPageChange(1, 10)
    }
    // 搜索
    onSearch(fieldsValue) {
        this.setState({
            pageData: {pageNo:1,pageSize:10}
        },()=>{
            this.getTimedTaskList(fieldsValue)
        })
    }
    // 分页
    onPageChange(pageNo, pageSize) {
        this.setState({
            pageData:{
                pageNo,
                pageSize,
            }
        },()=> {
            this.getTimedTaskList()
        })
        
    }
    // 初始化
    getTimedTaskList(fieldsValue) {
        const { pageNo, pageSize } = this.state.pageData
        if (fieldsValue && !_.isEmpty(fieldsValue.taskTime)) {
            fieldsValue.start = getDateTime3(fieldsValue.taskTime[0])+' 00:00:00'
            fieldsValue.stop = getDateTime3(fieldsValue.taskTime[1])+' 23:59:59'
            delete(fieldsValue.taskTime)
        }
        this.setState({
            queryFormFieldsValue: fieldsValue === undefined ? this.state.queryFormFieldsValue : { ...fieldsValue }
        },async () =>{
            const params = {
                pageNo, pageSize, queryFormFieldsValue: this.state.queryFormFieldsValue
            }
            store.dispatch({
                type: 'SaveSearchValues',
                data: {
                    pathName: 'tasklist',
                    ...params
                }
            })
            let res = await apiGetTimedTaskPage({
                ...this.state.queryFormFieldsValue,
                pageNo,
                pageSize,
            })
            if(res.rows && !res.code){
                this.setState({
                    tableSource:res.rows,
                    pageData:{
                        pageNo:res.pageNo,
                        pageSize:res.pageSize,
                    },
                    total:res.totalCount
                })
            }
        })
    }
    // 删除
    deletedTask = (couponTimerCenterId) => {
        React.$confirm({
            title: "提示",
            type: 'warning',
            content: "确定是否删除？",
            onOk: async () => {
                let res = await apiGetCouponTimerCenterDel({ couponTimerCenterId })
                if (res.code === 0) {
                    React.$message({
                        type: 'success',
                        content: '删除成功'
                    })
                    this.onPageChange(1, 10)
                } else {
                    React.$message({
                        type: 'warning',
                        content: res.codeMessage
                    })
                }
            }
        })
    }
    // 发送结果
    render() {
        const { isShowQueryForm, queryFormOptions, filterColumns, columns, pageData:{pageNo, pageSize}, total, tableSource } = this.state
        return (
            <div className="p-layout-box">
                <TheQueryForm
                    ref={(ref) => this.queryFormRef = ref}
                    show={isShowQueryForm}
                    option={queryFormOptions}
                    onReset={() => this.onReset()}
                    onGetValues={(fieldsValue) => this.onSearch(fieldsValue)}
                />
                <TheTableExtend
                    columns={columns}
                    onFormTrigger={() => this.setState({
                        isShowQueryForm: !this.state.isShowQueryForm
                    })}
                    onTableRefresh={() => this.getTimedTaskList()}
                    onColumnsFilter={(value) => this.setState({
                        filterColumns: value
                    })}
                >
                    <TheButton type="primary" haspermi={["couponManagement:task:add"]} size="middle" onClick={() => this.props.history.push('/couponManagement/timedTask/detail?type=create')}>创建</TheButton>
                </TheTableExtend>
                <TheTable scroll={{ x: 'max-content', y: '63vh' }} dataSource={tableSource} columns={filterColumns} />
                <ThePagination
                    pageNo={pageNo}
                    pageSize={pageSize}
                    total={total}
                    pageChange={(pageNo, pageSize) => this.onPageChange(pageNo, pageSize)}
                />
            </div>
        );
    }
}

export default TimedTask;
